package cn.sciento.starter.social.qq.connect;

import com.google.common.base.Charsets;
import org.apache.commons.lang3.StringUtils;
import cn.sciento.starter.social.core.common.connect.SocialTemplate;
import cn.sciento.starter.social.core.provider.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

public class QQTemplate extends SocialTemplate {
  private static final Logger LOGGER = LoggerFactory.getLogger(QQTemplate.class);
  
  public QQTemplate(Provider provider) {
    super(provider);
    setUseParametersForClientAuthentication(true);
  }
  
  protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
    String result = (String)getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
    if (StringUtils.isBlank(result))
      throw new RestClientException("access token endpoint returned empty result"); 
    LOGGER.debug("==> get qq access_token: " + result);
    String[] arr = StringUtils.split(result, "&");
    String accessToken = "", expireIn = "", refreshToken = "";
    for (String s : arr) {
      if (s.contains("access_token")) {
        accessToken = s.split("=")[1];
      } else if (s.contains("expires_in")) {
        expireIn = s.split("=")[1];
      } else if (s.contains("refresh_token")) {
        refreshToken = s.split("=")[1];
      } 
    } 
    return createAccessGrant(accessToken, null, refreshToken, Long.valueOf(expireIn), null);
  }
  
  protected RestTemplate createRestTemplate() {
    RestTemplate restTemplate = super.createRestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charsets.UTF_8));
    return restTemplate;
  }
}
